﻿using Common;
using Device;
using JQ50037.Procdure;
using JQ50037.View;
using LiveCharts;
using NewDevice;
using NewDevice.RS485;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Configuration;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Threading;

namespace JQ50037.ViewModel
{
    internal class MainViewModel : NotifyBase
    {
        #region 参数

        private int _goalTemp;

        public int GoalTemp
        {
            get { return _goalTemp; }
            set
            {
                _goalTemp = value;
                this.DoNotify();
            }
        }

        private double _minTemp;

        public double MinTemp
        {
            get { return _minTemp; }
            set
            {
                _minTemp = value;
                this.DoNotify();
            }
        }

        private double _maxTemp;

        public double MaxTemp
        {
            get { return _maxTemp; }
            set
            {
                _maxTemp = value;
                this.DoNotify();
            }
        }

        private double _liquidLevel;

        /// <summary>
        /// 液位
        /// </summary>
        public double LiquidLevel
        {
            get { return _liquidLevel; }
            set
            {
                _liquidLevel = value;
                this.DoNotify();
            }
        }

        private double _flowRateMin;

        public double FlowRateMin
        {
            get { return _flowRateMin; }
            set
            {
                _flowRateMin = value;
                this.DoNotify();
            }
        }

        private double _flowRateMax;

        public double FlowRateMax
        {
            get { return _flowRateMax; }
            set
            {
                _flowRateMax = value;
                this.DoNotify();
            }
        }

        private int _hours;

        public int Hours
        {
            get { return _hours; }
            set
            {
                _hours = value;
                this.DoNotify();
                TotalTime = $"{_hours}小时{_minutes}分钟";

                RunTimeSpan = TimeSpan.FromHours(_hours).Add(TimeSpan.FromMinutes(_minutes));
                //RemainingTime = RunTimeSpan.ToString(@"dd\:hh\:mm\:ss");
            }
        }

        private int _minutes;

        public int Minutes
        {
            get { return _minutes; }
            set
            {
                _minutes = value;
                this.DoNotify();

                TotalTime = $"{_hours}小时{_minutes}分钟";
                RunTimeSpan = TimeSpan.FromHours(_hours).Add(TimeSpan.FromMinutes(_minutes));
                //RemainingTime = RunTimeSpan.ToString(@"dd\:hh\:mm\:ss");
            }
        }

        public ObservableCollection<bool> DOStatus { get; set; }
        public ObservableCollection<bool> DIStatus { get; set; }

        private void InitParam()
        {
            Config config = Config.Load();
            GoalTemp = config.GoalTemp;
            Hours = config.Hours;
            Minutes = config.Minutes;
            MaxTemp = config.TemperatureMax;
            MinTemp = config.TemperatureMin;
            LiquidLevel = config.LiquidLevelMin;
            FlowRateMax = config.FlowRateMax;
            FlowRateMin = config.FlowRateMin;
        }

        #endregion 参数

        #region 监控参数

        private float _temp;

        /// <summary>
        /// 实时温度
        /// </summary>
        public float Temp
        {
            get { return _temp; }
            set
            {
                _temp = value;
                this.DoNotify();
            }
        }

        private double _liquidHeight;

        /// <summary>
        /// 实时液位高度
        /// </summary>
        public double LiquidHeight
        {
            get { return _liquidHeight; }
            set
            {
                _liquidHeight = value;
                this.DoNotify();
            }
        }

        private string _remainingTime;

        public string RemainingTime
        {
            get { return _remainingTime; }
            set
            {
                _remainingTime = value;
                this.DoNotify();
            }
        }

        private float _flowRate;

        /// <summary>
        /// 实时流量
        /// </summary>
        public float FlowRate
        {
            get { return _flowRate; }
            set
            {
                _flowRate = value;
                this.DoNotify();
            }
        }

        private float _totalFlow;

        /// <summary>
        /// 总流量
        /// </summary>
        public float TotalFlow
        {
            get { return _totalFlow; }
            set
            {
                _totalFlow = value;
                this.DoNotify();
            }
        }

        private string _pauseButtonContent;

        public string PauseButtonContent
        {
            get { return _pauseButtonContent; }
            set
            {
                _pauseButtonContent = value;
                this.DoNotify();
            }
        }

        private bool _pauseButtonEnable;

        public bool PauseButtonEnable
        {
            get { return _pauseButtonEnable; }
            set
            {
                _pauseButtonEnable = value;
                this.DoNotify();
            }
        }

        private IOModule IO;

        private void EmgStopAction()
        {
            if (_isEmgStopSingal)
            {
                _isEmgStopSingal = false;

                try
                {
                    Log = "设备急停!";
                    IO.SetDOValue((int)DODefine.YUp, 0);
                    IO.SetDOValue((int)DODefine.YDown, 0);
                }
                catch (Exception ex)
                {
                    Log = ex.Message;
                }
            }
        }

        private bool isTesting = false;

        private void StartAction()
        {
            if (isTesting)
            {
                return;
            }
            Log = "开始测试";
            Start(null);
        }

        private void InitDevice()
        {
            try
            {

                IO = new IOModule();
                IO.IOModuleType = IOModuleType.All;
                IO.Connect();

                IO.ListDIChanged.Add(new DIChanged { DIndex = (int)DIDefine.EmgStop, ConditionValue = false, DIChangedEvent = EmgStopAction });
                IO.ListDIChanged.Add(new DIChanged { DIndex = (int)DIDefine.EmgStop, ConditionValue = true, DIChangedEvent = () => { _isEmgStopSingal = true; } });
                IO.ListDIChanged.Add(new DIChanged { DIndex = (int)DIDefine.Start, ConditionValue = true, DIChangedEvent = StartAction });
                IO.ListDIChanged.Add(new DIChanged { DIndex = (int)DIDefine.Safe, ConditionValue = false, DIChangedEvent = () => { _isSafeLineSingal = false; } });
                IO.ListDIChanged.Add(new DIChanged { DIndex = (int)DIDefine.Safe, ConditionValue = true, DIChangedEvent = () => { _isSafeLineSingal = true; } });

                SetLed(2);

                Task.Run(() =>
                {
                    while (true)
                    {
                        try
                        {
                            refresh = true;

                            for (int i = 0; i < 16; i++)
                            {
                                DIStatus[i] = IO.GetDIValue(i);
                            }
                            for (int i = 0; i < 16; i++)
                            {
                                DOStatus[i] = IO.GetDOValue(i);
                            }
                            refresh = false;
                            Thread.Sleep(400);
                        }
                        catch (Exception ex)
                        {
                            Mylog.Error(ex, ex.Message);
                        }
                    }
                });

                SerialBase serial = new SerialBase();
                serial.Connect(Config.Load().DevicePort, 9600);
                LiquidLevelGauge liq = new LiquidLevelGauge(serial);
                FlowMeter_LWGY lwgy = new FlowMeter_LWGY(serial);
                ALT_HSM alt = new ALT_HSM(serial);


                Task.Run(() => {
                    while (true) {

                        //5分钟超过10次通信异常则报警
                        Thread.Sleep(1000 * 60 * 5);
                        comErrCount = 0;
                    }
                
                });

                //后台循环监控液位、温度、流量
                Task.Run(() =>
                {
                    while (true)
                    {
                        Stopwatch sw = Stopwatch.StartNew();
                        try
                        {
                            var liqHeight = liq.GetLiquidLevel(3);  //读取液位
                            LiquidHeight = liqHeight;
                            Wait(300);

                            var temp = alt.GetTemperature(4);   // 读取温度
                            Temp = temp;
                            Wait(300);

                            var traf = lwgy.GetRealtimeTraffic(6);  //实时流量
                            FlowRate = traf;
                            Wait(300);

                            var totalTraf = lwgy.GetTotalTraffic(6);    //累计流量
                            TotalFlow = (float)Math.Round(totalTraf, 3);
                            Wait(1000);

                            StartDataUpdate();
                        }
                        catch (Exception ex)
                        {
                            Mylog.Error(ex, ex.Message);
                            comErrCount++;
                            if (comErrCount > 10)
                            {
                                Log = "通信异常!";
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                Mylog.Error(ex,ex.Message);
                Log = ex.Message;
              
            }
            
        }
        int comErrCount = 0;
        private void Wait(int millSecond)
        {
            Stopwatch sw = Stopwatch.StartNew();
            while (sw.ElapsedMilliseconds<millSecond)
            {

            }
        }

        #endregion 监控参数

        private string _log;
        private bool refresh;

        public string Log
        {
            get { return _log; }
            set
            {
                _log = value;
                this.DoNotify();
            }
        }

        private readonly Random _random = new Random();

        // 温度数据
        public ChartValues<float> TempChartValues { get; set; }

        // 液位深度数据
        public ChartValues<double> LiqHeightChartValues { get; set; }

        // 实时流量数据
        public ChartValues<float> FlowRateChartValues { get; set; }

        public ObservableCollection<string> LineChartLabels { get; set; }

        public MainViewModel()
        {
            SetParamCommand = new CommandBase(SetParam);
            StartCommand = new CommandBase(Start);
            ResetCommand = new CommandBase(Reset);
            PauseCommand = new CommandBase(Pause);

            InitParam();

            DIStatus = new ObservableCollection<bool>();
            for (int i = 0; i < 16; i++)
            {
                DIStatus.Add(true);
            }
            DOStatus = new ObservableCollection<bool>();
            for (int i = 0; i < 16; i++)
            {
                DOStatus.Add(true);
            }
            DOStatus.CollectionChanged += DOStatus_CollectionChanged;

            // 初始化折线图和柱状图的数据
            TempChartValues = new ChartValues<float>();
            LiqHeightChartValues = new ChartValues<double>();
            FlowRateChartValues = new ChartValues<float>();
            LineChartLabels = new ObservableCollection<string>();

            InitDevice();

            RunTime = $"已运行{0}小时{0}分钟";
            //开始记录油温、液位、流速
            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        string fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".csv";
                        Random random = new Random();
                        double oilTemperature = Temp; // 油温（0-100℃）
                        double liquidLevel = LiquidHeight;   // 液位（0-100%）
                        double flowRate = FlowRate;       // 流量（0-50 m³/h）

                        // 将数据写入CSV文件
                        WriteToCsv(fileName, oilTemperature, liquidLevel, flowRate);

                        // 等待1分钟
                        Thread.Sleep(60000);
                    }
                    catch (Exception ex)
                    {
                        Log = ex.Message;
                    }
                };
            });

            IsRunning = false;
            PauseButtonEnable = false;
            PauseButtonContent = "暂停";

            Log = "设备初始化完成";
        }

        private ManualResetEvent _pauseEvent = new ManualResetEvent(true); // 初始为已触发状态

        private void Pause(object obj)
        {
            try
            {
                if (PauseButtonContent == "暂停")
                {
                    PauseButtonContent = "继续";
                    _pauseEvent.Set();
                    DOEnable = true;
                    IO.SetDOValue((int)DODefine.OilIn, 0);
                    IO.SetDOValue((int)DODefine.OilOut, 0);
                }
                else
                {
                    PauseButtonContent = "暂停";
                    IO.SetDOValue((int)DODefine.OilIn, 1);
                    IO.SetDOValue((int)DODefine.OilOut, 1);
                    DOEnable = false;
                    Log = "5s后继续运行";
                    Task.Run(() =>
                    {
                        Thread.Sleep(5000);
                        _pauseEvent.Reset();
                    });
                }
            }
            catch (Exception ex)
            {
                Log = ex.Message + "!";
            }
        }

        #region 气缸动作

        private bool _isEmgStopSingal;
        private bool _isSafeLineSingal;
        private bool IsBusy;

        private bool _startButtonEnable;

        public bool StartButtonEnable
        {
            get { return _startButtonEnable; }
            set
            {
                _startButtonEnable = value;
                this.DoNotify();
            }
        }

        private bool _resetButtonEnable;

        public bool ResetButtonEnable
        {
            get { return _resetButtonEnable; }
            set
            {
                _resetButtonEnable = value;
                this.DoNotify();
            }
        }

        private bool _setParamButtonEnable;

        public bool SetParamButtonEnable
        {
            get { return _setParamButtonEnable; }
            set
            {
                _setParamButtonEnable = value;
                this.DoNotify();
            }
        }

        private bool _doEnable;

        public bool DOEnable
        {
            get { return _doEnable; }
            set
            {
                _doEnable = value;
                this.DoNotify();
            }
        }

        private bool _isRunning;

        public bool IsRunning
        {
            get { return _isRunning; }
            set
            {
                _isRunning = value;
                DOEnable = !value;
                PauseButtonEnable = value;
                StartButtonEnable = !value;
                ResetButtonEnable = !value;
                SetParamButtonEnable = !value;
                this.DoNotify();
            }
        }

        private static void WriteToCsv(string fileName, double oilTemperature, double liquidLevel, double flowRate)
        {
            // 检查文件是否存在，如果不存在则创建文件并写入表头
            if (!File.Exists(fileName))
            {
                using (StreamWriter sw = new StreamWriter(fileName))
                {
                    sw.WriteLine("DateTime,OilTemperature (℃),LiquidLevel (mm),FlowRate (m³/h)");
                }
            }

            // 追加写入数据
            using (StreamWriter sw = new StreamWriter(fileName, true))
            {
                string line = $"{DateTime.Now},{Math.Round( oilTemperature,3)},{Math.Round( liquidLevel,3)},{Math.Round( flowRate,3)}";
                sw.WriteLine(line);
            }

            Console.WriteLine($"数据已写入文件: {fileName}");
        }

        private void YDown()
        {
            //if (!_isSafeLineSingal)
            //{
            //    Log = "安全光栅触发!";
            //    return;
            //}
            if (!_isEmgStopSingal)
            {
                Log = "急停触发!";
                return;
            }
            Log = "开始气缸到位";
            IO.SetDOValue((int)DODefine.YUp, 0);
            IO.SetDOValue((int)DODefine.YDown, 1);
            ManualResetEventSlim LocationCompletedEvent = new ManualResetEventSlim(false);
            bool waiting = true;
            Task.Run(() =>
            {
                while (waiting)
                {
                    if (IO.GetDIValue((int)DIDefine.YDown))
                    {
                        IO.SetDOValue((int)DODefine.YUp, 0);
                        IO.SetDOValue((int)DODefine.YDown, 1);
                        LocationCompletedEvent.Set();
                        break;
                    }
                    if (!_isEmgStopSingal)
                    {
                        LocationCompletedEvent.Set();
                        break;
                    }

                    //if (!_isSafeLineSingal || !_isEmgStopSingal)
                    if (!_isEmgStopSingal)
                    {
                        IO.SetDOValue((int)DODefine.YUp, 0);
                        IO.SetDOValue((int)DODefine.YDown, 0);
                        LocationCompletedEvent.Set();
                        break;
                    }
                    Thread.Sleep(10);
                };
            });
            if (!LocationCompletedEvent.Wait(10000))
            {
                waiting = false;
                IO.SetDOValue((int)DODefine.YUp, 0);
                IO.SetDOValue((int)DODefine.YDown, 0);
                throw new Exception("气缸到位超时");
            }

            //if (!_isSafeLineSingal)
            //{
            //    Log = "安全光栅触发!";
            //    return;
            //}
            if (!_isEmgStopSingal)
            {
                Log = "急停触发!";
                return;
            }
            Log = "气缸到位完成";
        }

        private void YUp()
        {
            //if (!_isSafeLineSingal)
            //{
            //    Log = "安全光栅触发!";
            //    return;
            //}
            if (!_isEmgStopSingal)
            {
                Log = "急停触发!";
                return;
            }

            IO.SetDOValue((int)DODefine.YUp, 1);
            IO.SetDOValue((int)DODefine.YDown, 0);
            ManualResetEventSlim LocationCompletedEvent = new ManualResetEventSlim(false);
            bool waiting = true;
            Task.Run(() =>
            {
                while (waiting)
                {
                    if (IO.GetDIValue((int)DIDefine.YUp))
                    {
                        LocationCompletedEvent.Set();
                        break;
                    }

                    if (!_isEmgStopSingal)
                    {
                        LocationCompletedEvent.Set();
                        break;
                    }

                    //if (!_isSafeLineSingal)
                    //{
                    //    IO.SetDOValue((int)DODefine.YUp, 0);
                    //    IO.SetDOValue((int)DODefine.YDown, 0);
                    //    LocationCompletedEvent.Set();
                    //    break;
                    //}
                    Thread.Sleep(10);
                };
            });
            if (!LocationCompletedEvent.Wait(10000))
            {
                waiting = false;
                IO.SetDOValue((int)DODefine.YUp, 0);
                IO.SetDOValue((int)DODefine.YDown, 0);
                throw new Exception("电缸复位超时");
            }
            IO.SetDOValue((int)DODefine.YUp, 0);
            IO.SetDOValue((int)DODefine.YDown, 0);
            Log = "气缸复位完成";
        }

        #endregion 气缸动作

        private void Reset(object obj)
        {
            try
            {
                IO.SetDOValue((int)DODefine.Heat, 0);
                IO.SetDOValue((int)DODefine.OilOut, 0);
                IO.SetDOValue((int)DODefine.OilIn, 0);
                YUp();
                SetLed(2);
                PauseButtonContent = "暂停";
                Log = "复位完成";

                RunTime = $"已运行{0}小时{0}分钟";
            }
            catch (Exception ex)
            {
                Log = ex.Message + "!";
            }
        }

        private string _totalTime;

        public string TotalTime
        {
            get { return _totalTime; }
            set
            {
                _totalTime = value;
                this.DoNotify();
            }
        }

        private string _runTime;

        public string RunTime
        {
            get { return _runTime; }
            set
            {
                _runTime = value;
                this.DoNotify();
            }
        }

        private void Start(object obj)
        {
            Task.Run(() =>
            {
                isTesting = true;
                for (int i = 0; i < 1; i++)
                {
                    //SN = (i + 1).ToString();

                    if (!_isEmgStopSingal)
                    {
                        Log = "设备急停!";
                        return;
                    }
                    //if (!_isSafeLineSingal)
                    //{
                    //    Log = "安全光栅触发!";
                    //    return;
                    //}
                    if (IsBusy)
                    {
                        Log = "正在进行其他操作,请完成后再尝试!";
                        return;
                    }

                    IsBusy = true;
                    IsRunning = true;
                    IsRunFinished = false;

                    try
                    {
                        SetLed(3);
                        // 下压
                        YDown();
                        Log = "气缸到位";
                        var config = Config.Load();
                        IO.SetDOValue((int)DODefine.Heat, 1);   // 加热
                        Log = "开始加热";

                        IO.SetDOValue((int)DODefine.OilIn, 1);
                        IO.SetDOValue((int)DODefine.OilOut, 1);
                        //Thread.Sleep(3000);

                        bool isHeatTimeout = false;

                        // 开始
                        Log = "开始运行";
                        startTime = DateTime.Now;
                        RunTime = $"已运行{0}小时{0}分钟";
                        TimeSpan runnedTimeSpan = TimeSpan.Zero;
                        _pauseEvent.Set();
                        Task.Run(() =>
                        {
                            while (IsRunning)
                            {
                                _pauseEvent.WaitOne();
                                runnedTimeSpan = runnedTimeSpan.Add(TimeSpan.FromSeconds(1));
                                var remainingTimeSpan = (RunTimeSpan - (DateTime.Now - startTime));
                                if (remainingTimeSpan.TotalSeconds <= 0)
                                {
                                    IsRunFinished = true;
                                    break;
                                }
                                RunTime = $"已运行{(int)runnedTimeSpan.TotalHours}小时{runnedTimeSpan.Minutes}分钟";
                                Thread.Sleep(1000);
                            }
                        });

                        Task.Run(() =>
                        {
                            Thread.Sleep(2 * 60 * 60 * 1000);
                            isHeatTimeout = true;
                        });
                        while (Temp < config.TemperatureMin)
                        {
                            if (isHeatTimeout)
                            {
                                throw new Exception("加热油温超时");
                            }
                            if (!_isEmgStopSingal)
                            {
                                throw new Exception("设备急停");
                            }
                            //if (!_isSafeLineSingal)
                            //{
                            //    throw new Exception("安全光栅触发");
                            //}
                        }

                        while (!IsRunFinished)
                        {
                            if (!_isEmgStopSingal)
                            {
                                throw new Exception("设备急停");
                            }
                            //if (!_isSafeLineSingal)
                            //{
                            //    throw new Exception("安全光栅触发");
                            //}

                            // 温度判定
                            if (Temp < config.TemperatureMin || Temp > config.TemperatureMax)
                            {
                                throw new Exception("油温超出设定范围");
                            }

                            // 液位判定
                            if (LiquidHeight < config.LiquidLevelMin)
                            {
                                throw new Exception("液位过低");
                            }

                            // 流量判定
                            if (PauseButtonContent == "继续")
                            {
                                if (FlowRate < config.FlowRateMin || FlowRate > config.FlowRateMax)
                                {
                                    throw new Exception("流速超出设定范围");
                                }
                            }

                            // 控制油温
                            if (Temp < config.GoalTemp - 2)
                            {
                                IO.SetDOValue((int)DODefine.Heat, 1);
                            }
                            if (Temp > config.GoalTemp -1)
                            {
                                IO.SetDOValue((int)DODefine.Heat, 0);
                            }
                        }
                        IO.SetDOValue((int)DODefine.Heat, 0);
                        IO.SetDOValue((int)DODefine.OilOut, 0);
                        Thread.Sleep(3000);
                        IO.SetDOValue((int)DODefine.OilIn, 0);

                        YUp();
                        Log = "运行完成";
                    }
                    catch (Exception ex)
                    {
                        Log = ex.Message + "!";
                        Mylog.Error(ex, ex.Message);
                        SetLed(1);
                    }
                    finally
                    {
                        IsBusy = false;
                        IsRunning = false;
                        IO.SetDOValue((int)DODefine.Heat, 0);
                        IO.SetDOValue((int)DODefine.OilOut, 0);
                        IO.SetDOValue((int)DODefine.OilIn, 0);
                    }
                }
                isTesting = false;
            });
        }

        private DateTime startTime;
        private TimeSpan RunTimeSpan;
        private bool IsRunFinished;

        /// <summary>
        /// 设置报警灯指示状态
        /// </summary>
        /// <param name="ryg">1 Red  2 yellow 3 green </param>
        private void SetLed(int ryg)
        {
            switch (ryg)
            {
                case 1:
                    IO.SetDOValue((int)DODefine.Red, 1);
                    IO.SetDOValue((int)DODefine.Yellow, 0);
                    IO.SetDOValue((int)DODefine.Green, 0);
                    break;

                case 2:
                    IO.SetDOValue((int)DODefine.Red, 0);
                    IO.SetDOValue((int)DODefine.Yellow, 1);
                    IO.SetDOValue((int)DODefine.Green, 0);
                    break;

                case 3:
                    IO.SetDOValue((int)DODefine.Red, 0);
                    IO.SetDOValue((int)DODefine.Yellow, 0);
                    IO.SetDOValue((int)DODefine.Green, 1);
                    break;

                default:
                    break;
            }
        }

        private void DOStatus_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (!refresh)
            {
                int index = e.NewStartingIndex;
                int value = (sender as ObservableCollection<bool>)[index] ? 1 : 0;
                IO.SetDOValue(index, value);
            }
        }

        private void SetParam(object obj)
        {
            try
            {
                var win = new SetParamView();
                win.Topmost = true;
                win.Show();
                win.Closed += Win_Closed;
            }
            catch (Exception ex)
            {
                Log = ex.ToString() + "!";
            }
        }

        private void Win_Closed(object sender, EventArgs e)
        {
        }

        public CommandBase SetParamCommand { get; set; }
        public CommandBase ResetCommand { get; set; }
        public CommandBase StartCommand { get; set; }
        public CommandBase PauseCommand { get; set; }

        private void StartDataUpdate()
        {
            int totalCount = 60;
            Application.Current.Dispatcher.Invoke(() =>
            {
                TempChartValues.Add(Temp);
                LiqHeightChartValues.Add(LiquidHeight);
                FlowRateChartValues.Add(FlowRate);
                LineChartLabels.Add(DateTime.Now.ToString("HH:mm:ss"));

                if (TempChartValues.Count > totalCount)
                {
                    TempChartValues.RemoveAt(0);
                    LiqHeightChartValues.RemoveAt(0);
                    FlowRateChartValues.RemoveAt(0);
                    LineChartLabels.RemoveAt(0);
                }
            });
        }
    }
}